/**
 * 
 */
package com.hk.Mgr.web.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.hk.commons.StringHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.sys.SysRoleReq;
import com.hk.Mgr.web.message.sys.SysRoleRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.entity.sys.SysRole;
import com.hk.commons.entity.sys.SysRoleModules;
import com.hk.service.sys.ISysRole;
import com.hk.service.sys.ISysRoleModules;

/**
 * @author lemon 系统角色实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/SysRoleCtrl")
public class SysRoleCtrl extends BaseCtrl {

	@Autowired
	private ISysRole sysRoleService;

	@Autowired
	private ISysRoleModules sysRoleModulesService;

	/**
	 * @Title: getSysRoleById
	 * @Description: 根据id获取系统角色
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysRoleById", method = RequestMethod.POST)
	public ResponseBase<SysRoleRes> getSysRoleById(@RequestBody SysRoleReq req) {
		ResponseBase<SysRoleRes> resp = new ResponseBase<SysRoleRes>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysRole sysRole = sysRoleService.findById(req.getId());

			SysRoleRes sresp = new SysRoleRes();
			ReqToModelHelper.copyReqValueToModel(sysRole, sresp);
			List<SysRoleModules> sysRoleModuleList = sysRoleModulesService
					.getByRoleId(sysRole.getId());
			sresp.setSysRoleModuleList(sysRoleModuleList);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(sresp);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getSysRoleList
	 * @Description: 分页获取系统角色
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysRoleList", method = RequestMethod.POST)
	public ResponseBase<List<SysRoleRes>> getSysRoleList(
			@RequestBody SysRoleReq req) {
		ResponseBase<List<SysRoleRes>> resp = new ResponseBase<List<SysRoleRes>>();
		HqlFilter hqlFilter = new HqlFilter();
		if (StringUtils.isNotEmpty(req.getName())) {
			hqlFilter.addEQFilter("name", req.getName());
		}

		if(req.getRoleType() != null){
			hqlFilter.addEQFilter("roleType", req.getRoleType());
		}
		hqlFilter.addSort("id");
		hqlFilter.addOrder("desc");
		try {
			List<SysRoleRes> respList = new ArrayList<SysRoleRes>();

			List<SysRole> retList = sysRoleService.findByFilter(hqlFilter,
					req.getCurPage(), req.getPageSize());

			for (SysRole sysRole : retList) {
				SysRoleRes sresp = new SysRoleRes();
				sresp.setSysRole(sysRole);
				ReqToModelHelper.copyReqValueToModel(sysRole, sresp);
				List<SysRoleModules> sysRoleModuleList = sysRoleModulesService
						.getByRoleId(sysRole.getId());
				sresp.setSysRoleModuleList(sysRoleModuleList);
				respList.add(sresp);
			}
			Long total = sysRoleService.countByFilter(hqlFilter);
			resp.setSize(total);

			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(respList);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: saveSysRole
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveSysRole", method = RequestMethod.POST)
	public ResponseBase<SysRole> saveSysRole(@RequestBody SysRoleReq req) {
		ResponseBase<SysRole> resp = new ResponseBase<SysRole>();
		try {
			SysRole model = new SysRole();
			String sysModuleIds = req.getSysModuleIds();
			req.setSysModuleIds(null);
			ReqToModelHelper.copyReqValueToModel(req, model);
			model.setCreatedts(this.getCurrentTime());
			model.setCreator(this.getAccount());
			Long saveId = sysRoleService.add(model);

			resp.setResult(model);
			saveOrUpdateSysRoleModule(saveId, sysModuleIds);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("添加成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: saveOrUpdateSysUserRoles
	 * @Description: 保存或更新角色模块关联表信息
	 * @param sysRoleId
	 *            角色ID
	 * @param sysModuleIds
	 *            模块ID集合
	 */
	private void saveOrUpdateSysRoleModule(Long sysRoleId, String sysModuleIds) {
		if (sysRoleId != null) {
			String[] moduleIds = sysModuleIds.split(",");
			List<SysRoleModules> sysRoleModulesList = sysRoleModulesService
					.getByRoleId(sysRoleId);
			// 先删除后添加，效率更快
			for (SysRoleModules sysRoleModules : sysRoleModulesList) {
				sysRoleModulesService.delete(sysRoleModules.getId());
			}
			for (String moduleId : moduleIds) {
				SysRoleModules new_srm = new SysRoleModules();
				new_srm.setRoleId(sysRoleId);
				if(StringHelper.isNotEmpty(moduleId)){
					new_srm.setModuleId(Long.parseLong(moduleId));
				}
				// 新增
				sysRoleModulesService.add(new_srm);
			}
		}
	}

	/**
	 * @Title: updateSysRole
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updateSysRole", method = RequestMethod.POST)
	public ResponseBase<SysRole> updateSysRole(@RequestBody SysRoleReq req) {
		ResponseBase<SysRole> resp = new ResponseBase<SysRole>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysRole model = sysRoleService.findById(req.getId());
			String sysModuleIds = req.getSysModuleIds();
			req.setSysModuleIds(null);
			ReqToModelHelper.copyReqValueToModel(req, model);

			model.setUpdatedts(this.getCurrentTime());

			sysRoleService.update(model);
			saveOrUpdateSysRoleModule(model.getId(), sysModuleIds);

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: deleteSysRole
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteSysRole", method = RequestMethod.POST)
	public ResponseBase deleteSysRole(@RequestBody SysRoleReq req) {
		ResponseBase resp = new ResponseBase();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			sysRoleService.delete(req.getId());

			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("删除成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

}
